package com.huanzhidadi.redis.redisson;

import org.redisson.Redisson;
import org.redisson.RedissonRedLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

import java.util.concurrent.TimeUnit;

/**
 * 红锁
 */
public class Redlock {
    public static void main(String[] args) {
        // 节点1
        Config config1 = new Config();
        config1.useSingleServer().setAddress("redis://192.168.2.132:6311");
        RedissonClient redissonClient1 = Redisson.create(config1);

        // 节点2
        Config config2 = new Config();
        config2.useSingleServer().setAddress("redis://192.168.2.132:6311");
        RedissonClient redissonClient2 = Redisson.create(config2);

        // 节点3
        Config config3 = new Config();
        config3.useSingleServer().setAddress("redis://192.168.2.132:6311");
        RedissonClient redissonClient3 = Redisson.create(config3);

        String resourceName = "LOCK_KEY";

        RLock lock1 = redissonClient1.getLock(resourceName);
        RLock lock2 = redissonClient2.getLock(resourceName);
        RLock lock3 = redissonClient3.getLock(resourceName);

        // 向3个redis示例尝试加锁
        RedissonRedLock redLock = new RedissonRedLock(lock1, lock2, lock3);
        boolean isLock;
        try {
            // 500ms拿不到锁，就认为获取锁失败，10000ms是锁失效时间
            isLock = redLock.tryLock(500, 10000, TimeUnit.MILLISECONDS);
            System.out.println("isLock: " + isLock);
            if (isLock) {
                // 业务代码

            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 释放锁
            redLock.unlock();
        }
    }
}
